import axios from 'axios';
import { getToken, setToken, getTKenType } from '@/utils/auth';
import msg from '@/utils/layer';
import settings from '@/settings.js';
import { useUserStore } from '@/store/modules/user.js'; //路由
import common from '@/utils/common';

// 创建axios实例
const service = axios.create({
	baseURL: baseConfig.baseUrl + '/api/', // url = base url + request url
	// withCredentials: true, // 跨域请求时发送cookie
	timeout: 60 * 1000, //60分钟
	// 设置默认get和post的请求头
	headers: {
		get: {
			'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
		},
		post: {
			'Content-Type': 'application/json;charset=utf-8',
		},
	},
});
let isLog = true;
// 请求拦截器
service.interceptors.request.use(
	(config) => {
		//添加token
		const token = getToken();
		const TKenType = getTKenType();
		if (token) {
			config.headers['AUTHORIZATION'] = `${TKenType} ${token}`;
		}
		//添加全局参数-post请求
		if (config.method == 'post') {
			if (!Array.isArray(config.data) && config.headers['Content-Type'] != 'multipart/form-data') {
				config.data = {
					...config.data,
				};
				if(config.data.optype && config.url.indexOf('optype') == -1) {
					//如果有optype值，把optype值赋值到url上
					config.url = `${config.url}${config.url.indexOf('?') == -1 ? '?' : '&'}optype=${config.data.optype}`
				}
			}
		} else {
			// get请求
			config.params = {
				...config.params,
			};
		}
		return config;
	},
	(error) => {
		return Promise.reject(error);
	}
);

// 响应拦截器
service.interceptors.response.use(
	/**
	 * 获得http标头或状态等信息 response => response
	 */

	/**
	 * 确定自定义代码的请求状态
	 * 通过HTTP状态代码判断状态
	 */
	(response) => {
		//登录即将超时如果还在操作，则重新绑定新的token
		// console.log('查看header' , response);
		if (response.headers && response.headers['x-refresh-token']) {
			const new_token = response.headers['x-refresh-token'];
			const expires = response.headers['expires']
			if (new_token) {
				const store = useUserStore(); //pinia
				// console.log('查看header----X-Refresh-Token' , new_token);
				// console.log('查看header----expires' , expires);
				// 缓存超时时间
				store.exp = expires;
				// 缓存token
				setToken(new_token);
				store.token = new_token;
			}
		}
		const res = response.data;
		const code = res.code;
		if (code != 100) {
			const errorMsg = '请求接口异常！错误代码：[' + code + ']，原因：' + res.msg;
			if (code === 401) {
				if (isLog) {
					loginOut();
				}
			} else {
				msg.err(errorMsg);
			}
			return Promise.reject(res);
		} else {
			return res;
		}
	},
	(error) => {
		let errorInfo = '',
			code = 500;
		if (error.response && error.response.data) {
			errorInfo = error.response.data.msg || error.response.statusText;
			code = error.response.data.code || error.response.status;
		} else {
			errorInfo = error;
		}

		if ((error.response && code === 401)) {
			if (isLog) {
				loginOut();
			}
		} else {
			const errorMsg = `请求接口异常！错误代码：[${code}]，原因：${errorInfo || '网络超时！'} `;
			msg.err(errorMsg);
		}
		return Promise.reject(error);
	}
);

function loginOut() {
	isLog = false;
	// common.loginOut()	//退出登录
}

export default service;